import React, { Component } from 'react'
import { View, Text, Button, StyleSheet, TextInput } from 'react-native'

export default class FetchDemoPage extends Component {
	constructor(props) {
		super(props)
		this.state = {
			showText: ''
		}
	}

	loadData() {
		let url = `https://api.github.com/search/repositories?q=${this.searchKey}`
		fetch(url)
			.then(response => {
				if (response.ok) {
					return response.text()
				} else {
					throw new Error('Network response was not work!')
				}
			})
			.then(responseText => {
				this.setState({
					showText: responseText
				})
			})
			.catch(e => {
				this.setState({
					showText: e.toString()
				})
			})
	}

	render() {
		return (
			<View style={styles.container}>
				<Text style={styles.welcome}>Fetch 使用</Text>
				<View style={styles.input_container}>
					<TextInput
						style={styles.input}
						onChangeText={text => {
							this.searchKey = text
						}}
					/>
					<Button title={'fetch data'} onPress={() => this.loadData()} />
				</View>
				<Text>{this.state.showText}</Text>
			</View>
		)
	}
}

const styles = StyleSheet.create({
	container: {
		flex: 1,
		backgroundColor: '#f5fcff'
	},
	welcome: {
		fontSize: 16,
		textAlign: 'center'
	},
	input_container: {
		flexDirection: 'row',
		alignItems: 'center'
	},
	input: {
		height: 30,
		flex: 0.9,
		borderColor: 'black',
		borderWidth: 1
	}
})
